<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Area;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AreaGetterController extends Controller
{
    public function province()
    {
        $provinces = Area::where('level', 1)->get();

        $data = [];

        foreach ($provinces as $province) {
            $data[] = [
                'id'        => $province->id,
                'name'      => $province->name,
                'parent_id' => $province->parent_id,
                'parent'    => $province->parent()->count() ? $province->parent->name : '',
            ];
        }

        return success_return(['list' => $data]);
    }

    public function city($province_id = null)
    {
        try {
            $data = [];
            if ($province_id) {
                $province = Area::where('level', 1)->whereId($province_id)->firstOrFail();

                $cities = $province->children;
            } else {
                $cities = Area::where('level', 2)->get();
            }

            foreach ($cities as $city) {
                $data[] = [
                    'id'        => $city->id,
                    'name'      => $city->name,
                    'parent_id' => $city->parent_id,
                    'parent'    => $city->parent->name,
                ];
            }

            return success_return(['list' => $data]);
        } catch (ModelNotFoundException $e) {
            return success_return(null);
        }
    }

    public function county($city_id = null)
    {
        try {
            $data = [];
            if ($city_id) {
                $city = Area::where('level', 2)->whereId($city_id)->firstOrFail();

                $counties = $city->children;
            } else {
                $counties = Area::where('level', 3)->get();
            }

            foreach ($counties as $county) {
                $data[] = [
                    'id'        => $county->id,
                    'name'      => $county->name,
                    'parent_id' => $county->parent_id,
                    'parent'    => $county->parent->name,
                ];
            }

            return success_return(['list' => $data]);
        } catch (ModelNotFoundException $e) {
            return success_return(null);
        }
    }
}
